package work.xiaohong.jijin.time;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import work.xiaohong.jijin.controller.LiangHuaController;
import work.xiaohong.jijin.entity.Free;
import work.xiaohong.jijin.entity.HttpResult;
import work.xiaohong.jijin.entity.Store;
import work.xiaohong.jijin.entity.lianghua.LiangHuaQuery;
import work.xiaohong.jijin.entity.lianghua.LiangHuaReponse;
import work.xiaohong.jijin.entity.lianghua.LiangHuaUser;
import work.xiaohong.jijin.feign.QQEmailFeign;
import work.xiaohong.jijin.service.IFreeService;
import work.xiaohong.jijin.service.IStoreService;
import work.xiaohong.jijin.util.JijinHttpUtil;
import work.xiaohong.jijin.util.JijinUrlUtil;
import work.xiaohong.model.Result;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author xiaohong
 * @Description 定时爬取最新内容存入数据库并更新redis
 * @date 2020/12/4 0004 11:01
 */
@Component
@Slf4j
public class MySqlTask {

    @Autowired
    public IStoreService iStoreService;

    @Autowired
    private IFreeService iFreeService;

    @Autowired
    private LiangHuaController liangHuaController;

    @Autowired
    private QQEmailFeign qqEmailFeign;

    public static void main(String[] args) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar calendar=Calendar.getInstance();
        System.out.println("今天是"+weekDays[calendar.get(Calendar.DAY_OF_WEEK)-1]);
    }

    /**
     * 工作日的14:50执行一次，看看有没有出现买点和卖点
     */
    @Scheduled(cron = "0 50 14 * * ?")
    public void CheckTask() throws Exception {

        Calendar calendar=Calendar.getInstance();
        // {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
        // 周末不上班
        if(calendar.get(Calendar.DAY_OF_WEEK) == 1 && calendar.get(Calendar.DAY_OF_WEEK) == 7){
            return;
        }

        LiangHuaUser user = liangHuaController.Login().getData();
        LiangHuaQuery query = new LiangHuaQuery();
        query.setAlipayid(user.getAlipayid());
        query.setAuthtoken(user.getAuthtoken());
        List<LiangHuaReponse> result = liangHuaController.getAll(query).getData();

        Map<String,String> buyResult = new HashMap();
        Map<String,String> sellResult = new HashMap();
        for (LiangHuaReponse liangHuaReponse : result) {
            if (liangHuaReponse.getIdea() == 2){
                buyResult.put(liangHuaReponse.getCode(),liangHuaReponse.getName());
            }else if (liangHuaReponse.getIdea() == 3){
                sellResult.put(liangHuaReponse.getCode(),liangHuaReponse.getName());
            }
        }

        String message = "";
        HashMap<String, Map<String, String>> messageMap = new HashMap<>();

        if (buyResult.size() <= 0 && sellResult.size() <= 0){
            message = "今日无操作!";
        }else {
            if (buyResult.size() > 0){
                messageMap.put("买入操作：",buyResult);
            }

            if (sellResult.size() > 0){
                messageMap.put("卖出操作：",sellResult);
            }

            message = JSON.toJSONString(messageMap).replaceAll("\\{","").replaceAll("}","");
        }

        qqEmailFeign.sendTxtMail("1990063814@qq.com","今日份操作",message);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info(format.format(new Date()) + "--------交易检查完成");
    }

    /**
     * 每天的23:00执行一次，计算卖出买入数据
     */
    @Scheduled(cron = "0 00 23 * * ?")
    public void JijinTask() throws Exception {

        // 获取所有交易中的数据
        List<Store> list = iStoreService.findIsDoing();

        // 判断是卖出还是买入
        for (Store jj : list) {

            Store resultJijin = new Store();

            // 获取目前基金净值
            String url = JijinUrlUtil.creatUrl(jj.getCode(), 13);
            HttpResult httpResult = JijinHttpUtil.sendGetReq(url);
            Float nav = httpResult.getGsz();  //获取当前净值

            DecimalFormat df = new DecimalFormat("0.00");

            if (jj.getStatus() == 3){
                // 卖出
                resultJijin.setId(jj.getId());
                resultJijin.setSellPrice(nav);
                resultJijin.setSellMoney(
//                    df.format(
//                    Float.parseFloat(jj.getBuyNumber())*nav
//                    )
                        jj.getBuyNumber()*nav
                );
                resultJijin.setStatus(4);
                resultJijin.setSellDay(LocalDateTime.now());
                resultJijin.setDealDay(LocalDateTime.now());
            }else{
                // 买入
                resultJijin.setBuyPrice(nav);
                Float number = jj.getBuyMoney()/nav;
                // 保留两位小数
//                resultJijin.setBuyNumber(df.format(number));
                resultJijin.setBuyNumber(number);
                resultJijin.setStatus(1);
//                resultJijin.setFreeDay(8);
                resultJijin.setId(jj.getId());
                resultJijin.setDealDay(LocalDateTime.now());
            }

            // 保存数据库
            iStoreService.updateById(resultJijin);
//            System.out.println(resultJijin);
//            Thread.sleep(5000);
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info(format.format(new Date()) + "-------完成计算任务");


    }


    /**
     * 每天的00:01执行一次，更新可赎份额
     */
    @Transactional
    @Scheduled(cron = "0 01 00 * * ?")
    public void freeNumberTask() throws Exception {

        // 遍历所有订单，将可赎天数减少1
        List<Store> all = iStoreService.findIsNotFree();
        for (Store store : all) {
            if (store.getFreeDay() != null && store.getFreeDay() != 0){
                Store uStore = new Store();
                uStore.setFreeDay(store.getFreeDay()-1);
                uStore.setId(store.getId());
                //更新基金
                iStoreService.updateById(uStore);
                if (uStore.getFreeDay() == 0){
                    //更新可赎份额
                    Free free = new Free();
                    free.setCode(store.getCode());
                    Free one = iFreeService.getOne(new QueryWrapper<>(free));
                    if (one != null){
                        Free uFree = new Free();
                        uFree.setId(one.getId());
                        uFree.setFreeNumber(one.getFreeNumber()+store.getBuyNumber());
                        iFreeService.updateById(uFree);
                    }else  {
                        System.out.println("没有该基金的可赎份额记录,现在创建");
                        Free uFree = new Free();
                        uFree.setCode(store.getCode());
                        uFree.setFreeNumber(store.getBuyNumber());
                        uFree.setName(store.getName());
                        iFreeService.save(uFree);
                    }

                }
            }
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info(format.format(new Date()) + "------完成更新可赎份额任务");

    }


}
